from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

from apps.courses.models import Courses, CourseTag, CourseResourse, Video, CourseDiscuss
from apps.operation.models import UserFavorite, UserCourse, CourseComments, CourseDiscussComment

'''课程作业'''


class CourseHomeWork(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, *args, **kwargs):
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()
        print(course.discuss_all())

        # 1. 用户和课程之间的关联
        # 2. 对view进行login登录的验证
        # 3. 其他课程

        # 查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()
        #
        # #学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        related_courses = set(related_courses)
        #
        course_resources = CourseResourse.objects.filter(course=course)
        # # 分页
        # paginator = Paginator(comments, 7)
        # try:
        #     page = request.GET.get('page', 1)
        # except Exception:
        #     page = 1
        # comments = paginator.get_page(page)

        return render(request, 'course_homework.html', {"course": course,
                                                        "course_resources": course_resources,
                                                        "related_courses": related_courses})


'''课程讨论详情'''

'''我醉了，写的啥玩意？？？？赶紧结束啊！！！！！2023.1.7 22.56'''


class CourseDiscussDetail(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, discuss_id, *args, **kwargs):
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()
        coursediscuss = CourseDiscuss.objects.get(id=int(discuss_id))
        coursediscuss.read_nums += 1
        coursediscuss.save()
        # 查询出话题所有的评论
        # comment_list=[]
        comments = coursediscuss.coursediscusscomment_set.all().order_by('-add_time')
        # print(comments.title)
        # for comment in comments:
        #     comment_list.append(comment.comments)
        # print(comment_list)

        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()
        #
        # #学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        #
        related_courses = set(related_courses)
        course_resources = CourseResourse.objects.filter(course=course)
        # 分页
        paginator = Paginator(comments, 5)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        comments = paginator.get_page(page)

        return render(request, "course_discuss_detail.html", {
            "course": course,
            "course_resources": course_resources,
            "related_courses": related_courses,
            "comments": comments,
            "coursediscuss": coursediscuss,
        })

    def post(self, request, *args, **kwargs):
        # return
        page_num = request.POST.get("current_page_num", 1)
        score = request.POST.get("score")
        comment_id = request.POST.get("comment_id")
        course_id = request.POST.get("course_id")
        coursediscuss_id = request.POST.get("coursediscuss_id")
        CourseDiscussComment.objects.filter(id=comment_id).update(score=score)

        print(page_num, score, coursediscuss_id, course_id, comment_id)
        return redirect("/course/{0}/discuss/{1}?page={2}".format(course_id, coursediscuss_id, page_num))


'''课程讨论话题展示'''


class CourseDiscussList(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, *args, **kwargs):
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()
        print(course.discuss_all())

        # 1. 用户和课程之间的关联
        # 2. 对view进行login登录的验证
        # 3. 其他课程

        # 查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()
        #
        # #学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        #
        related_courses = set(related_courses)
        course_resources = CourseResourse.objects.filter(course=course)
        # # 分页
        # paginator = Paginator(comments, 7)
        # try:
        #     page = request.GET.get('page', 1)
        # except Exception:
        #     page = 1
        # comments = paginator.get_page(page)

        return render(request, "course_discuss.html", {
            "course": course,
            "course_resources": course_resources,
            "related_courses": related_courses
        })


'''视频播放'''


class VideoView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, video_id, *args, **kwargs):
        """
        获取课程章节信息
        """
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()

        video = Video.objects.get(id=int(video_id))

        # 查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()

        # 学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        related_courses = set(related_courses)
        course_resources = CourseResourse.objects.filter(course=course)

        return render(request, "course-play.html", {
            "course": course,
            "course_resources": course_resources,
            "related_courses": related_courses,
            "video": video,
        })


'''课程视频评论展示'''


class CourseVideoCommentsView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, *args, **kwargs):
        video_id = request.GET.get("video_id")
        # go_url=request.META.get("HTTP_REFERER",'')
        # video_id=go_url.split("/")[-1]
        # print(go_url,video_id)
        video = Video.objects.get(id=int(video_id))
        print(video)
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()

        comments = CourseComments.objects.filter(course=course).order_by('-add_time')
        print(comments)
        # 查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()

        # 学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        print(related_courses)
        related_courses = set(related_courses)
        course_resources = CourseResourse.objects.filter(course=course)
        # 分页
        paginator = Paginator(comments, 7)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        comments = paginator.get_page(page)

        return render(request, "course-play-comment.html", {
            "course": course,
            "course_resources": course_resources,
            "related_courses": related_courses,
            "comments": comments,
            # 'go_url':go_url,
            "video": video
        })


'''评论展示'''


class CourseCommentsView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, *args, **kwargs):
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()

        comments = CourseComments.objects.filter(course=course).order_by('-add_time')
        print(comments)
        # 查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()

        # 学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        related_courses=set(related_courses)
        print(related_courses)
        course_resources = CourseResourse.objects.filter(course=course)
        # 分页
        paginator = Paginator(comments, 7)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        comments = paginator.get_page(page)

        return render(request, "course-comment.html", {
            "course": course,
            "course_resources": course_resources,
            "related_courses": related_courses,
            "comments": comments
        })


'''课程章节展示'''


class CourseLessonView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, course_id, *args, **kwargs):
        """
        获取课程章节信息
        """
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()

        # 1. 用户和课程之间的关联
        # 2. 对view进行login登录的验证
        # 3. 其他课程

        # 查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

            course.students += 1
            course.save()
        #
        # #学习过该课程的所有同学
        user_courses = UserCourse.objects.filter(course=course)
        user_ids = [user_course.user.id for user_course in user_courses]
        all_courses = UserCourse.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:5]
        # # related_courses = [user_course.course for user_course in all_courses if user_course.course.id != course.id]
        related_courses = []
        for item in all_courses:
            if item.course.id != course.id:
                related_courses.append(item.course)
        #
        related_courses = set(related_courses)
        course_resources = CourseResourse.objects.filter(course=course)

        return render(request, "course-video.html", {
            "course": course,
            "course_resources": course_resources,
            "related_courses": related_courses
        })


'''课程详情'''


class CourseDetailView(View):
    def get(self, request, course_id, *args, **kwargs):
        """
        获取课程详情
        """
        course = Courses.objects.get(id=int(course_id))
        course.click_nums += 1
        course.save()

        # 获取收藏状态
        has_fav_course = False
        has_fav_org = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course.id, fav_type=1):
                has_fav_course = True
            if UserFavorite.objects.filter(user=request.user, fav_id=course.course_org.id, fav_type=2):
                has_fav_org = True

        # 通过课程的tag做课程的推荐
        # 单个标签
        # tag = course.tag
        # related_courses = []
        # if tag:
        #     related_courses = Courses.objects.filter(tag=tag).exclude(id__in=[course.id])[:3]

        tags = course.coursetag_set.all()
        tag_list = [tag.tag for tag in tags]

        course_tags = CourseTag.objects.filter(tag__in=tag_list).exclude(course__id=course.id)
        related_courses = set()
        for course_tag in course_tags:
            related_courses.add(course_tag.course)
        # 学习这门课程的用户

        return render(request, "course-detail.html", {
            "course": course,
            "has_fav_course": has_fav_course,
            "has_fav_org": has_fav_org,
            "related_courses": related_courses
        })


'''课程列表'''


class CourseListView(View):
    def get(self, request, *args, **kwargs):
        all_courses = Courses.objects.all().order_by('-add_time')
        hot_courses = Courses.objects.order_by("-click_nums")[:3]
        # 搜索关键词
        keywords = request.GET.get("keywords", "")
        s_type = "course"
        if keywords:
            all_courses = all_courses.filter(
                Q(name__icontains=keywords) | Q(desc__icontains=keywords) | Q(desc__icontains=keywords))

        # 课程排序
        sort = request.GET.get("sort", "")
        if sort == "students":
            all_courses = all_courses.order_by("-students")
        elif sort == "hot":
            all_courses = all_courses.order_by("-click_nums")
        # 分页
        paginator = Paginator(all_courses, 12)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        all_courses = paginator.get_page(page)
        return render(request, "course-list.html", {"all_courses": all_courses, "sort": sort,
                                                    "hot_courses": hot_courses, "keywords": keywords, "sort": sort,
                                                    "s_type": s_type})
